import * as vscode from "vscode"
const md5 = require("md5")
const axios = require("axios")
const appid = "20210929000959942"
const secret = "j3STJyEEXF6YmTCKZMdM"
interface baidu {
    trans_result: Array<dst>
    error_code?: string
}
interface dst {
    dst: string
}
// 请求百度翻译函数
const translate = async (q: string, from: string, to: string) => {
    const salt = Math.random()
    const {data}: {data: baidu} = await axios({
        method: "get",
        url: "https://fanyi-api.baidu.com/api/trans/vip/translate",
        params: {
            from,
            to,
            appid,
            q,
            salt,
            sign: md5(appid + q + salt + secret)
        }
    })
    if (data.error_code == "54003") {
        vscode.window.showErrorMessage("请求过于频繁，请控制在1s请求一次")
        return ""
    }
    const {dst} = data.trans_result[0]
    // 转换驼峰
    const result = dst
        .split(" ")
        .map((v: string, i: number) => {
            return i !== 0 ? v.charAt(0).toLocaleUpperCase() + v.slice(1) : v.toLocaleLowerCase()
        })
        .join("")
    // 去除多余标点符号符
    return result.replace(/[.,;':"]/g, "")
}
// 判断字符串是否全为中文
function isChinese(temp: string): boolean {
    return /[^\u4e00-\u9fa5]/.test(temp) ? false : true
}
export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand("translate.zn", async () => {
        const {activeTextEditor} = vscode.window // 获取当前聚焦的文本编辑器
        // activeTextEditor!.selection 当前选中的范围
        const currentSelect = activeTextEditor!.document.getText(activeTextEditor!.selection) // 根据范围获取选中文本
        // 已选择文本 并且是纯中文字符串
        if (currentSelect && isChinese(currentSelect)) {
            const result = await translate(currentSelect, "zh", "en")
            activeTextEditor!.edit(editBuilder => {
                editBuilder.replace(activeTextEditor!.selection, result)
            })
        } else {
            vscode.window.showInformationMessage("请核实是否选中了中文文本")
        }
    })
    context.subscriptions.push(disposable)
}
export function deactivate() {}
